/*
 * @Author: Mr.Cong Wei
 * @Date: 2022-03-29 12:10:31
 * @LastEditTime: 2022-12-22 19:28:47
 */
import qs from 'qs'
import { apiConfiger } from 'iv-npm/packages/shared'
import Request from '../utils/http/index'
import { TIME_OUT } from '../setting/server.seeting'
import type { MyRequestConfig } from '../utils/http/type'
// import { useStore } from 'vuex';
// const store = useStore();

const request = new Request({
  baseURL: process.env.NODE_ENV == 'development' ? '/api' : '',
  timeout: TIME_OUT,
  headers: {
    'Content-Type': 'application/json;charset=UTF-8',
    // "Content-Type": "multipart/form-data",
    'Accept-Language': 'zh-Hans'
  },
  interceptors: {
    // 请求拦截器
    requestInterceptors: (config: any) => {
      config.headers.authorization = localStorage.getItem('token') ? `Bearer ${localStorage.getItem('token')}` : null
      return apiConfiger(config)
    },
    // 响应拦截器
    responseInterceptors: result => {
      return result
    }
  }
})

/**
 * @description: 函数的描述
 * @interface D 请求参数的interface
 * @interface T 响应结构的intercept
 * @param {MyRequestConfig} config 不管是GET还是POST请求都使用data
 * @returns {Promise}
 */
const cwRequest = <D, T = any>(config: MyRequestConfig<D>) => {
  const { method = 'GET' } = config
  if (method === 'get' || method === 'GET') {
    config.paramsSerializer = params => {
      return qs.stringify(params, { arrayFormat: 'repeat' })
    }
    for (const i in config.data) {
      if (config.data[i] === null || config.data[i] === undefined) {
        delete config.data[i]
      }
    }
    config.params = config.data
  }
  return request.request<T>(config)
}
// 取消请求
export const cancelRequest = (url: string | string[]) => {
  return request.cancelRequest(url)
}
// 取消全部请求
export const cancelAllRequest = () => {
  return request.cancelAllRequest()
}

export default cwRequest
